<template>
	<div>
		<ProTable ref="proTable" title="经销商认证" :columns="columns" :requestApi="getTableList" :init-param="initParam">
			<!-- 表格 功能 按钮 -->
			<template #otherButton>
				<el-button v-auth="'user:dealer:authentication:export:invoke'" @click="onExport"> 导出 </el-button>
			</template>
			<!-- 表单 头部 数据 -->
			<template #tableHeader>
				<el-tabs v-model="activeTag" class="demo-tabs" @tab-click="handleTab">
					<el-tab-pane v-for="item in tags" :key="item.name" :label="`${item.label}(${item.data})`" :name="item.name"></el-tab-pane>
				</el-tabs>
			</template>
			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>

			<!-- 表格操作 -->
			<template #operation="{ row }">
				<el-button type="primary" link v-if="row.verify == 1" v-auth="'user:dealer:authentication:audit:invoke'" @click="onAudit(row)">
					审核
				</el-button>
			</template>
		</ProTable>
		<Audit :visible="auditVisible" :row="auditRow" @handleClose="closeAudit"></Audit>
	</div>
</template>

<script setup lang="tsx" name="userDealerAuth">
import { onMounted, ref, reactive, computed, nextTick, onBeforeMount } from 'vue';
import dayjs from 'dayjs';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { NextLoading } from '/@/utils/loading';
import ProTable from '../../../../components/ProTable/index.vue';
import { ProTableInstance, ColumnProps } from '../../../../components/ProTable/interface';
import { fetchDealerAuthStatics, fetchDealerAuthList, fetchExportDealerAuth } from '/@/api/user';
import { useDownload } from '/@/hooks/useDownload';
import Audit from './dialog/audit.vue';

import default_photo from '/@/assets/images/default_photo.jpg';

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

const router = useRouter();
const route = useRoute();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	paramCode: 'id',
	paramTimeType: 'request',
});

const activeTag = ref<any>('0');
const tags = ref<any>([
	{
		label: '全部状态',
		name: '0',
		data: 1100,
	},
	{
		label: '等待认证',
		name: '1',
		data: 0,
	},
	{
		label: '认证成功',
		name: '2',
		data: 0,
	},
	{
		label: '认证失败',
		name: '3',
		data: 0,
	},
]);

const handleTab = () => {
	nextTick(() => {
		proTable.value?.getTableList();
	});
};

const initStatics = async (params: any) => {
	const { code, data } = await fetchDealerAuthStatics(params);
	if (code == 200) {
		tags.value = [
			{
				label: '全部状态',
				name: '0',
				data: data.total,
			},
			{
				label: '等待认证',
				name: '1',
				data: data.checking,
			},
			{
				label: '认证成功',
				name: '2',
				data: data.passed,
			},
			{
				label: '认证失败',
				name: '3',
				data: data.failed,
			},
		];
	}
};

const getParams = (params: any) => {
	let data = {
		...params,
		status: activeTag.value,
	};
	if (data.paramValue) {
		data[data.paramCode] = data.paramValue;
		delete data.paramValue;
		delete data.paramCode;
	}
	if (data.paramTime) {
		data[`${data.paramTimeType}StartTime`] = dayjs(data.paramTime[0]).format('YYYY-MM-DD');
		data[`${data.paramTimeType}EndTime`] = dayjs(data.paramTime[1]).format('YYYY-MM-DD');
		delete data.paramTimeType;
		delete data.paramTime;
	}
	return data;
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const getTableList = (params: any) => {
	const data = getParams(params);
	initStatics(data);
	return fetchDealerAuthList(data);
};

// 表格配置项
const columns: ColumnProps<any>[] = [
	{
		prop: 'paramValue',
		label: '用户搜索',
		isShow: false,
		search: {
			span: 2,
			xs: 1,
			sm: 1,
			md: 2,
			lg: 1,
			xl: 1,
			render: (scope: any) => {
				const slot = {
					prepend: () => (
						<el-select
							v-model={scope.searchParam.paramCode}
							placeholder="Select"
							style="width: 100px"
							onChange={(value) => (scope.searchParam.paramCode = value)}
						>
							{searchArr.map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
					),
				};
				return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={50}></el-input>;
			},
		},
	},
	{
		prop: 'paramTime',
		label: '时间筛选',
		isShow: false,
		search: {
			span: 2,
			xs: 1,
			sm: 1,
			md: 2,
			lg: 1,
			xl: 1,
			render: (scope: any) => {
				return (
					<div class="flex-center">
						<el-select
							v-model={scope.searchParam.paramTimeType}
							placeholder="Select"
							style="width: 100px"
							class="mini-gray-select flex-shrink"
							onChange={(value) => (scope.searchParam.paramTimeType = value)}
						>
							{[
								{
									label: '申请时间',
									value: 'request',
								},
							].map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
						<el-date-picker
							v-model={scope.searchParam.paramTime}
							type="datetimerange"
							start-placeholder="开始时间"
							end-placeholder="结束时间"
							format="YYYY-MM-DD HH:mm:ss"
							date-format="YYYY-MM-DD"
							time-format="HH:mm:ss"
						/>
					</div>
				);
			},
		},
	},
	{
		prop: 'id',
		label: '用户ID',
	},
	{
		prop: 'name',
		label: '用户信息',
		minWidth: 160,
		render: (scope) => {
			return (
				<div class="flex-center">
					<el-image src={scope.row.avatar || default_photo} style="width:40px;height:40px;flex-shrink:0" fit="cover"></el-image>
					<div style="text-align: left;" class="ml10">
						<el-link type="primary" underline={false} onClick={() => router.push(`/user/detail/${scope.row.id}`)}>
							{scope.row.nickName}
						</el-link>
						<div>{scope.row.mobile}</div>
					</div>
				</div>
			);
		},
	},
	{
		prop: 'requestTime',
		label: '申请时间',
		minWidth: 120,
	},
	{
		prop: 'companyName',
		label: '企业名称',
		minWidth: 120,
	},
	{
		prop: 'creditCode',
		label: '统一信用代码',
		minWidth: 120,
	},
	{
		prop: 'legalPersonName',
		label: '法人姓名',
		minWidth: 120,
	},
	{
		prop: 'legalPersonIdno',
		label: '身份证号',
		minWidth: 120,
	},
	{
		prop: 'verify',
		label: '认证状态',
		minWidth: 120,
		render: (scope: any) => {
			return (
				<span>
					{scope.row.verify == 1 ? '等待审核' : scope.row.verify == 2 ? '认证成功' : '认证失败'}
					{scope.row.verify == 3 && (
						<el-tooltip class="box-item" effect="light" content={scope.row.reason} placement="top">
							<el-icon color="red" class="mt-3 ml5" style="vertical-align: middle;">
								<WarningFilled />
							</el-icon>
						</el-tooltip>
					)}
				</span>
			);
		},
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 100, align: 'left' },
];

const searchArr = [
	{
		label: '用户ID',
		value: 'id',
	},
	{
		label: '用户昵称',
		value: 'nickName',
	},
	{
		label: '手机号',
		value: 'mobile',
	},
];

const getPlaceholder = computed(() => {
	const target = searchArr.find((item) => {
		return item.value == proTable.value?.searchParam.paramCode;
	});
	return target ? `输入${target?.label}搜索` : '';
});

const auditVisible = ref(false);
const auditRow = ref();

// 保存并导出
const onExport = () => {
	ElMessageBox.confirm('确认导出数据?', '温馨提示', { type: 'warning' }).then(() =>
		useDownload(fetchExportDealerAuth, '经销商认证数据', getParams(proTable.value?.searchParam))
	);
};

const onAudit = (row: any) => {
	auditVisible.value = true;
	auditRow.value = row;
};

const closeAudit = (success: boolean) => {
	auditVisible.value = false;
	if (success) {
		proTable.value?.getTableList();
	}
};

onBeforeMount(() => {
	activeTag.value = route.query.status || '0';
});
</script>

<style lang="scss">
.demo-tabs {
	.el-tabs__header {
		margin-bottom: 0;
	}
}
</style>
